package com.xnx3.wangmarket.serverless.controller;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.DateUtil;
import com.xnx3.exception.NotReturnValueException;
import com.xnx3.j2ee.Global;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.SystemService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.SpringUtil;
import com.xnx3.j2ee.util.SystemUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.wangmarket.admin.entity.Site;
import com.xnx3.wangmarket.admin.entity.SiteUser;
import com.xnx3.wangmarket.admin.util.SessionUtil;
import com.xnx3.wangmarket.admin.util.TemplateAdminMenu.TemplateMenuEnum;
import com.xnx3.wangmarket.agencyadmin.entity.Agency;
import com.xnx3.wangmarket.plugin.base.controller.BasePluginController;

/**
 * 安装
 * @author 管雷鸣
 */
@Controller(value="ServerLessInstallController")
@RequestMapping("/plugin/serverless/")
public class InstallController extends BasePluginController {
	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;
	@Resource
	private SystemService systemService;
	
	
	/**
	 * @param area obs的区域，传入如 cn-north-4
	 * @return 是否保存成功的结果。如果成功，返回当前登录用户的 sessionid，也就是token
	 */
	@RequestMapping(value="create.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO create(HttpServletRequest request, 
			@RequestParam(required = true , defaultValue="") String area){
		if(area == null || area.length() == 0) {
			return error("请选择你网站域名是否要备案");
		}
		
		//设置区域进行保存
		BaseVO areaVO = ((com.xnx3.wangmarket.plugin.huaWeiYunServiceCreate.controller.SetHuaWeiYunServiceCreatePluginController)SpringUtil.getBean("setHuaWeiYunServiceCreatePluginController")).setAreaSave(area);
		if(areaVO.getResult() - BaseVO.FAILURE == 0) {
			return error(areaVO.getInfo());
		}
		
		//自动开通存储文件等附件的obs存储同
		BaseVO createFileObsVO = ((com.xnx3.wangmarket.plugin.huaWeiYunServiceCreate.controller.ObsHuaWeiYunServiceCreatePluginController)SpringUtil.getBean("obsHuaWeiYunServiceCreatePluginController")).createOBS();
		if(createFileObsVO.getResult() - BaseVO.FAILURE == 0) {
			return error(createFileObsVO.getInfo());
		}
		
		
		//将当前默认的网站设置为219,也就是默认将219这个网站变为当前登录的网站管理后台
		Site site = sqlService.findById(Site.class, 219);

		User user = sqlService.findById(User.class, site.getUserid());
		userService.loginForUserId(request, user.getId());
		SiteUser siteUser = new SiteUser();
		//缓存进session
		com.xnx3.wangmarket.admin.util.SessionUtil.setSiteUser(siteUser);
		
		//将拥有所有功能的管理权限，将功能菜单全部遍历出来，赋予这个用户
		Map<String, String> menuMap = new HashMap<String, String>();
		for (TemplateMenuEnum e : TemplateMenuEnum.values()) {
			menuMap.put(e.id, "1");
		}
		SessionUtil.setSiteMenuRole(menuMap);
		
		//得到上级代理的信息
		Agency parentAgency = sqlService.findAloneBySqlQuery("SELECT * FROM agency WHERE userid = " + user.getReferrerid(), Agency.class);
		com.xnx3.wangmarket.agencyadmin.util.SessionUtil.setParentAgency(parentAgency);
		//缓存当前网站
		SessionUtil.setSite(site);
		
		//自动开通网站html所存放的OBS桶
		BaseVO createSiteObsVO = ((com.xnx3.wangmarket.plugin.htmlSeparate.controller.HuaWeiYunObsServicePluginController)SpringUtil.getBean("HuaWeiYunObsServicePluginController")).createOBS(request, SystemUtil.get("HUAWEIYUN_ACCESSKEYID"), SystemUtil.get("HUAWEIYUN_ACCESSKEYSECRET"), "obs."+SystemUtil.get("HUAWEIYUN_COMMON_ENDPOINT")+".myhuaweicloud.com");
		if(createSiteObsVO.getResult() - BaseVO.FAILURE == 0) {
			return error(createSiteObsVO.getInfo());
		}
		ConsoleUtil.info("已自动创建网站存放的OBS桶："+createSiteObsVO.getInfo());
		
		
		//设置当前网站生成使用华为云OBS
		BaseVO generateSiteVO = ((com.xnx3.wangmarket.plugin.htmlSeparate.controller.SetController)SpringUtil.getBean("HtmlSeparatePluginController")).save(request, "obs", createSiteObsVO.getInfo(), SystemUtil.get("HUAWEIYUN_ACCESSKEYID"), SystemUtil.get("HUAWEIYUN_ACCESSKEYSECRET"), "obs."+SystemUtil.get("HUAWEIYUN_COMMON_ENDPOINT")+".myhuaweicloud.com", "","","","");
		if(generateSiteVO.getResult() - BaseVO.FAILURE == 0) {
			return error(generateSiteVO.getInfo());
		}
		
		// 如果当前实在开发工具中运行调试，还要更新当地system表缓存，不然会被热部署影响导致取出的数据不对
		if(Global.isJarRun) {
			systemService.refreshSystemCache();
		}
		
		return success(request.getSession().getId());
	}
}